import json,math
import time

import requests

from utils.comm import get_ali_object

from utils.captcha.captcha import captcha
from flask import Blueprint, jsonify, make_response, redirect
from db import db
from utils.myredis import r
import datetime
from flask import current_app as app,request
user_blue = Blueprint('user',__name__)

@user_blue.route("/test")
def test():
    str = datetime.datetime.strftime(datetime.datetime.now(),'%Y-%m-%d %H:%M:%S')+"   "+request.path+"   error"
    app.logger.error(str)
    app.logger.info('info log')
    app.logger.warning('warning log')

    sql = "insert into user values(0,'aa22222','abc')"
    db.update(sql)
    db.commit()
    sql1 = "select * from user"
    res = db.find_all(sql1)
    print(res)
    return 'ok234234'

@user_blue.route('/getimagecode')
def getimagecode():
    name,text,img = captcha.generate_captcha()
    uuid = request.args.get('uuid')
    r.str_setex(uuid,text,100)
    res = make_response(img)
    res.headers['Content-Type'] = "image/jpg"
    return res

@user_blue.route('/sendsms',methods=['POST'])
def sendsms():
    data = json.loads(request.data)
    mobile = data['mobile']
    uuid = data['uuid']
    imagecode = data['imagecode']

    if not all([mobile,uuid,imagecode]):
        return jsonify({'msg':'参数不完整'})
    code = r.str_get(uuid)
    if code:
        if imagecode.lower() != code.decode().lower():
            return jsonify({'code':200,'msg':'图片验证码错误'})
        r.del_key(uuid)
    else:
        return jsonify({'code':200,'msg':'图片验证码失败'})
    v= r.str_get(mobile)
    if v:
        return jsonify({'code':200,'msg':'一分钟只能发送一次'})
    r.list_push('smsmobile',mobile)
    return jsonify({'code':200})
import time,random
from utils.comm import send_message
@user_blue.route('/send')
# 长期任务
def send():
    # 让任务一直执行
    while True:
        for i in range(2):
            len = r.list_len('smsmobile')
            if len >0:
                value = r.list_pop('smsmobile')
                print(value)
                # 获取单条数据
                mobile = value.decode()
                code = random.randint(10000,99999)
                res = send_message(mobile,code)
                print(res)
                r.str_setex(mobile,code,60)
        time.sleep(10)
# 账号密码登录
from utils.myjwt import  myjwt
@user_blue.route('/login',methods=['POST'])
def login():
    # 获取手机号和短息验证
    data = json.loads(request.data)
    mobile = data['mobile']
    smscode = data['smscode']
    newsms = r.str_get(mobile)
    if newsms:
        if smscode != newsms.decode():
            return jsonify({'code':400,'msg':'验证码错误'})
        r.del_key(mobile)
        sql = "select id  from users where mobile='%s'"%mobile
        user = db.findone(sql)
        if user:
            data = {'data':{'userid':user['id'],'mobile':['mobile'],'exptime':int(time.time())}}
            token = myjwt.jwt_encode(data)
            sql = "select * from users where mobile='%s'"%mobile
            res = db.findone(sql)
            if res:
                return jsonify({'code':200,'token':token,'userid':user['id'],'msg':'登录成功'})
        else:
            return jsonify({'code':400,',msg':'此用户不能登录'})
    else:
        return jsonify({'code':'验证码失效'})